package com.trnnn.strutslit;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;

import javax.servlet.AsyncContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionContext {
	
	private SessionContext() {
		session.set(this);
	}

	public static final ThreadLocal<SessionContext> session=new ThreadLocal<SessionContext>();
	
	private HttpServletRequest request;
	private HttpServletResponse response;
	private HttpSession httpSession;
	private Cookie[] httpCookies;
	private InputStream inputStream;
	private OutputStream outputStream;
	private Map<String,String[]> parameterMap;
	private AsyncContext asyncContext;
	private String contentType;
	private Enumeration<Locale> locale;
	
	public HttpServletRequest getRequest(){
		return this.request;
	}
	
	public HttpServletResponse getResponse(){
		return this.response;
	}
	
	public HttpSession getSession(){
		return this.httpSession;
	}
	
	public Cookie[] getCookies(){
		return this.httpCookies;
	}
	
	public InputStream getInputStream(){
		return this.inputStream;
	}
	public OutputStream getOutputStream(){
		return this.outputStream;
	}
	
	public Map<String,String[]> getParameters(){
		return this.parameterMap;
	}
	
	public String getParameter(String name){
		return this.request.getParameter(name);
	}
	
	public AsyncContext getAsyncContext(){
		return this.asyncContext;
	}
	
	public String getContentType(){
		return this.contentType;
	}
	
	public Enumeration<Locale> getLocales(){
		return this.locale;
	}
	
	public void setRequestCharacterEncoding(String charset) throws UnsupportedEncodingException{
		this.request.setCharacterEncoding(charset);
	}
	
	public void setResponseCharacterEncoding(String charset){
		this.response.setCharacterEncoding(charset);
	}
	
	
	public static SessionContext newInstance(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		SessionContext sessionContext=new SessionContext();
		sessionContext.request=request;
		sessionContext.response=response;
		sessionContext.httpSession=request.getSession(true);
		sessionContext.httpCookies=request.getCookies();
		sessionContext.inputStream=request.getInputStream();
		sessionContext.outputStream=response.getOutputStream();
		sessionContext.parameterMap=request.getParameterMap();
		sessionContext.asyncContext=request.getAsyncContext();
		sessionContext.contentType=request.getContentType();
		sessionContext.locale=request.getLocales();
		return sessionContext;
	}
	
	public static SessionContext getCurrentContext(){
		return session.get();
	}
}
